package com.lyhengtongwl.zqsnews.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lyhengtongwl.putorefresh.BaseBothListener;
import com.lyhengtongwl.putorefresh.PullToBothLayout;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.adapter.FoundRecycleAdapter;
import com.lyhengtongwl.zqsnews.base.BaseFragment;
import com.lyhengtongwl.zqsnews.entity.BaseEntity;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.ui.activity.WebActivity;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.utils.ToastUtil;
import retrofit2.Response;

/**
 * Created by Steven on 2019/1/4.
 */
public class FoundFragment extends BaseFragment {
    private boolean isFirst = true;//默认第一次加载
    private JSONArray newsList;//加载新闻列表
    private JSONArray loadList;//加载_
    @BindView(R.id.recycle)
    RecyclerView recyclerView;
    @BindView(R.id.pullRefresh)
    PullToBothLayout pullToRefresh_layout;

    @BindView(R.id.title_left)
    ImageView titleLeft;
    @BindView(R.id.title_mid)
    TextView titleMid;
    @BindView(R.id.view_status_bar_place)
    View statusBarPlace;

    private int pageNo = 1;//默认是第一页
    private int pageSize = 10;//默认 加载条数
    private boolean isRefresh = false;//是否是下拉刷新
    private boolean isLoadMore = false;//是否是 上拉加载

    private int pageCount = 1;//当前 页数
    private int totalPage = 1;//总页数
    private FoundRecycleAdapter foundRecycleAdapter = null;

    @SuppressLint("InflateParams")
    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.found_fragment, null);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ViewGroup.LayoutParams params = statusBarPlace.getLayoutParams();
        params.height = ScreenUtil.getStatusBarHeight(getContext());
        statusBarPlace.setLayoutParams(params);
        titleLeft.setVisibility(View.GONE);
        titleMid.setText("发现");
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        setListen();
    }

    private void setListen() {

        pullToRefresh_layout.setRefreshListener(new BaseBothListener() {
            @Override
            public void refresh() {
                isRefresh = true;
                pageNo = 1;
                pageSize = 10;
                loadData();
            }

            @Override
            public void loadMore() {
                if (pageCount < totalPage) {
                    isLoadMore = true;
                    pageNo++;
                    pageSize = 10;
                    loadData();
                } else {
                    pullToRefresh_layout.finishLoadMore();
                    ToastUtil.showShort(App.getContext(), "没有更多数据了！");
                }
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && isFirst) {
            isFirst = false;
            loadData();
        }
    }

    private void initAdapter() {
        foundRecycleAdapter = new FoundRecycleAdapter(newsList);
        foundRecycleAdapter.openLoadAnimation();
        int mFirstPageItemCount = 10;
        foundRecycleAdapter.setNotDoAnimationCount(mFirstPageItemCount);
        foundRecycleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String title = ((JSONObject) (JSON.toJSON(newsList.get(position)))).getString("title");
                String linkUrl = ((JSONObject) (JSON.toJSON(newsList.get(position)))).getString("linkUrl");
                startActivity(new Intent(getActivity(), WebActivity.class).putExtra("url", linkUrl).putExtra("title", title));
            }
        });
        foundRecycleAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        foundRecycleAdapter.isFirstOnly(false);//这个是关键的设置
        recyclerView.setAdapter(foundRecycleAdapter);
    }

    //加载数据
    private void loadData() {
        Task.getApiService().getNewsList(pageNo + "", pageSize + "").enqueue(new MyCallback<BaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                pullToRefresh_layout.finishRefresh();
                pullToRefresh_layout.finishLoadMore();
                if ("0".equals(response.body().getCode())) {
                    JSONObject object = ((JSONObject) (JSON.toJSON(response.body().getResult().get("pager"))));
                    pageCount = Integer.parseInt(object.getString("pageNo"));
                    totalPage = Integer.parseInt(object.getString("totalPage"));
                    if (isRefresh) {
                        isRefresh = false;
                        newsList.clear();
                        newsList .addAll(response.body().getResult().getJSONArray("newsList"));
                        foundRecycleAdapter.notifyDataSetChanged();
                    } else if (isLoadMore) {
                        isLoadMore = false;
                        loadList = response.body().getResult().getJSONArray("newsList");
                        newsList.addAll(loadList);
                        foundRecycleAdapter.notifyDataSetChanged();
                    } else {
                        newsList = response.body().getResult().getJSONArray("newsList");
                        if (foundRecycleAdapter==null){
                            initAdapter();
                        }else {
                            foundRecycleAdapter.notifyDataSetChanged();
                        }
                    }

                }
            }

            @Override
            protected void onFailure(Throwable t) {
                pullToRefresh_layout.finishRefresh();
                pullToRefresh_layout.finishLoadMore();
            }
        });
    }
}
